<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>管理员列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px" >
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">

                        <div class="layui-inline">
                            <label class="layui-form-label">角色名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <button type="submit" class="layui-btn" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>

                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-xs layui-btn-danger data-cont-reset" lay-event="power">授权</a>
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">修改</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>
<!-- 表单弹窗 -->
<script type="text/html" id="roleEditDialog">
    <form id="roleEditForm" lay-filter="roleEditForm" class="layui-form model-form"
          style="padding-right: 20px;">
        <input name="id" type="hidden"/>
        <div class="layui-row">
            <div class="layui-col-md6">

                <div class="layui-form-item">
                    <label class="layui-form-label layui-form-required">选择权限</label>
                    <div class="layui-input-block">
                        <div id="perTree"></div>
                    </div>
                </div>

            </div>
        </div>
        <div class="layui-form-item layui-input-block">
            <button class="layui-btn" lay-filter="roleEditSubmit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog" id="Cancel">取消</button>
        </div>
    </form>
</script>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'tree'], function () {
        const $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            tree = layui.tree;

        table.render({
            elem: '#currentTableId',
            url: '/role/queryAllRole',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'name', title: '角色名称', sort: true, minwidth: 120},
                {field: 'description', title: '描述', sort: true, minwidth: 120},
                {field: 'creator', title: '创建人', sort: true, minwidth: 120},
                {field: 'createTime', title: '创建时间', sort: true, minwidth: 120},
                {title: '操作', minwidth: 120, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line',
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            const datas = data.field;
            const name = datas.name;

            //执行搜索重载
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: {
                    name: name,
                }
            }, 'data');
            return false;
        });

        //监听表头添加和批量删除操作
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                const index = layer.open({
                    title: '添加角色',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['50%', '50%'],
                    content: '../../page/role/roleAdd.html',
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                const checkStatus = table.checkStatus('currentTableId');
                const data = checkStatus.data;
                if(data.length === 0){//如果没有选中信息
                    layer.msg("请选择要删除的记录信息");
                }else{
                    //获取记录信息的id集合,拼接的ids
                    const ids = getCheckedId(data);
                    layer.confirm('真的要删除吗？', function (index) {
                        //调用删除功能
                        deleteReaderByIds(ids,index);
                        layer.close(index);
                    });
                }
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        //获取选中记录的id信息
        function getCheckedId(data){
            const arr = [];
            for(let i=0; i<data.length; i++){
                arr.push(data[i].id);
            }
            //拼接id,变成一个字符串
            return arr.join(",");
        };

        //批量删除功能
        function deleteReaderByIds(ids ,index){
            $.ajax({
                url: "/role/deleteRole",
                type: "DELETE",
                data: {ids: ids},
                success: function (data) {
                    if (data.code === 1) {
                        layer.msg('删除成功', {
                            icon: 6,
                            time: 1500
                        }, function () {
                            parent.window.location.reload();
                            const iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);
                        });
                    } else {
                        layer.msg(data.msg);
                    }
                }
            });
        };

        //修改角色
        function updateById(id) {
            const index = layer.open({
                title: '修改角色',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['50%', '50%'],
                content: '/toRoleEdit?id='+id,
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        }

        //监听信息栏删除和编辑
        table.on('tool(currentTableFilter)', function (obj) {
            const data = obj.data;
            if (obj.event === 'edit') {
                updateById(data.id);
            } else if (obj.event === 'delete') {
                layer.confirm('真的要删除吗?', function (index) {
                    deleteReaderByIds(data.id,index);
                    layer.close(index);
                });
            }else {
                showEditModel(data);
            }
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            const idx = layer.open({
                type: 1,
                area: '500px',
                title: '授权',
                content: $('#roleEditDialog').html(),
                success: function (layero, dIndex) {
                    // 表单提交事件
                    form.on('submit(roleEditSubmit)', function (data) {
                        const perInput = $("input[name^='layuiTreeCheck']:checked");
                        if (perInput.size() === 0) {
                            layer.msg('请选择权限！');
                            return false;
                        }
                        const loadIndex = layer.load(2);
                        const submitData = data.field;
                        const ids = [];
                        perInput.each(function () {
                            ids.push(this.value);
                        });
                        const idStr = ids.join(',')
                        $.ajax({
                            url: "/RoleMenuSave",
                            type: "POST",
                            data: {id:mData.id,ids: idStr},
                            success: function (data) {
                                if (data.code === 1) {
                                    layer.msg('授权成功', {
                                        icon: 6,
                                        time: 1500
                                    }, function () {
                                        parent.window.location.reload();
                                        const iframeIndex = parent.layer.getFrameIndex(window.name);
                                        parent.layer.close(iframeIndex);
                                    });
                                } else {
                                    layer.msg(data.msg);
                                }
                            }
                        });
                        return false;
                    });

                    // 弹窗不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');

                    $('#Cancel').click(function () {
                        layer.close(idx);
                    });
                    initPermissionTree(mData);
                }
            });
        }

        function initPermissionTree(data) {
            $.get("/menu/initMenu",function (res) {
                tree.render({
                    elem: '#perTree' , //绑定元素
                    id:'perTree',
                    showCheckbox:true,
                    onlyIconControl:true,
                    spread:true,
                    data: res.data
                });
                if(data){
                    $.get('/queryRoleMenu?id='+data.id , function (codeData) {
                        tree.setChecked('perTree', codeData.data); //批量勾选
                    });
                }
            });
        }
    });
</script>
</body>
</html>